//
//  OrderDeatailViewController.m
//  Hxcsfw
//
//  Created by 企友软mac on 2018/2/7.
//  Copyright © 2018年 企友软mac. All rights reserved.
//

#import "OrderDeatailViewController.h"
#import "UIImageView+WebCache.h"
#import "IAPHelper.h"
#import "IAPProduct.h"
#import "VideoDetailViewController.h"

@interface OrderDeatailViewController () <UIAlertViewDelegate>{
    UIView *bgView;
    UIView *payView;
    IAPProduct *product;
}

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topH;

@property (nonatomic, strong) IAPHelper  *m_iapHelper;
@property (nonatomic, strong) NSMutableArray *m_productArray;

@property (weak, nonatomic) IBOutlet UILabel *lbState;
@property (weak, nonatomic) IBOutlet UIImageView *imgVideo;
@property (weak, nonatomic) IBOutlet UILabel *lbTitle;
@property (weak, nonatomic) IBOutlet UILabel *lbPrice;
@property (weak, nonatomic) IBOutlet UILabel *lbOrderNum;
@property (weak, nonatomic) IBOutlet UILabel *lbTime;
@property (weak, nonatomic) IBOutlet UIButton *btnPay;
@property (weak, nonatomic) IBOutlet UIButton *btnDelete;
@property (weak, nonatomic) IBOutlet UIView *viewPay;

@end

@implementation OrderDeatailViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    if (XIPHONE) {
        _topH.constant = 88;
    }
    _btnPay.layer.masksToBounds = YES;
    _btnPay.layer.cornerRadius = 15;
    _btnPay.layer.borderWidth = 1.;
    _btnPay.layer.borderColor = [UIColor redColor].CGColor;

    _btnDelete.layer.masksToBounds = YES;
    _btnDelete.layer.cornerRadius = 15;
    _btnDelete.layer.borderWidth = 1.;
    _btnDelete.layer.borderColor = WColorFromHexToRGB(0x666666).CGColor;

    self.lbTitle.text = self.myOrderModel.KC_NAME;
    [self.imgVideo sd_setImageWithURL:[NSURL URLWithString:self.myOrderModel.PICURL] placeholderImage:[UIImage imageNamed:@"school_image.png"]];
    self.lbPrice.text = [NSString stringWithFormat:@"￥%@",self.myOrderModel.KC_PRICE];

    self.lbOrderNum.text = self.myOrderModel.ORDERNO;

    self.lbTime.text = [WShareUtil timeFormat:self.myOrderModel.JFRQ];

    if ([[self.myOrderModel ZFJG] isEqualToString:@"0"]) {
        [self.lbState setTextColor:[UIColor redColor]];
        self.lbState.text = @"未支付";
        self.viewPay.hidden = NO;
    } else {
        [self.lbState setTextColor:WRGBColor(54, 157, 46)];
        self.lbState.text = @"已支付";
        self.viewPay.hidden = YES;
    }

    [self loadData];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySuccess) name:@"PaySuccess" object:nil];//注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payFlase) name:@"PayFlase" object:nil];//注册通知
}

- (void)paySuccess {
    [self removePayView];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)payFlase {
    [self removePayView];
}

- (void)createPayView {
    bgView = [[UIView alloc] initWithFrame:self.view.bounds];
    bgView.backgroundColor = WRGBAColor(0, 0, 0, 0.5);
    [self.view addSubview:bgView];

    payView = [[UIView alloc] initWithFrame:CGRectMake(0, WSCREENH_HEIGHT - 180, WSCREENH_WIDTH, 180)];
    payView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:payView];

    UILabel *lbTit = [[UILabel alloc] initWithFrame:CGRectMake((WSCREENH_WIDTH - 80) * 0.5, 5, 80, 44)];
    lbTit.text = @"付款";
    lbTit.textAlignment = NSTextAlignmentCenter;
    [lbTit setTextColor:[UIColor blackColor]];

    //分割线
    UILabel *lbLine = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, WSCREENH_WIDTH, 1)];
    lbLine.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
    
    UIButton *btnClose = [[UIButton alloc] initWithFrame:CGRectMake(WSCREENH_WIDTH - 30, 18, 15, 15)];
    [btnClose setImage:[UIImage imageNamed:@"GB.png"] forState:UIControlStateNormal];
    [btnClose addTarget:self action:@selector(removePayView) forControlEvents:UIControlEventTouchUpInside];

    UILabel *lbPay = [[UILabel alloc] initWithFrame:CGRectMake((WSCREENH_WIDTH - 50) * 0.5 - 25, 60, 50, 44)];
    lbPay.text = @"支付";
    lbPay.textAlignment = NSTextAlignmentCenter;
    [lbPay setTextColor:[UIColor blackColor]];

    UILabel *lbMoney = [[UILabel alloc] initWithFrame:CGRectMake((WSCREENH_WIDTH - 50) * 0.5 + 25, 60, 50, 44)];

    lbMoney.text = [NSString stringWithFormat:@"￥%@",self.myOrderModel.KC_PRICE];
    lbMoney.textAlignment = NSTextAlignmentCenter;
    [lbMoney setTextColor:[UIColor colorWithRed:0.95 green:0.44 blue:0.23 alpha:1]];

    UIButton *btnPay = [[UIButton alloc] initWithFrame:CGRectMake(20, 110, WSCREENH_WIDTH - 40, 40)];
    btnPay.layer.masksToBounds = YES;
    btnPay.layer.cornerRadius = 5;
    btnPay.backgroundColor = [UIColor colorWithRed:0.95 green:0.29 blue:0 alpha:1];
    [btnPay setTitle:@"确认支付" forState:UIControlStateNormal];
    [btnPay setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

    [btnPay addTarget:self action:@selector(btnPayAppClick) forControlEvents:UIControlEventTouchUpInside];

    [payView addSubview:lbTit];
    [payView addSubview:lbLine];
    [payView addSubview:btnClose];
    [payView addSubview:lbPay];
    [payView addSubview:lbMoney];
    [payView addSubview:btnPay];
}

- (void)removePayView {
    [payView removeFromSuperview];
    [bgView removeFromSuperview];
}

- (void)btnPayAppClick {
    [self requestBuyCourse: self.myOrderModel.KC_ID];
}

- (void)requestBuyCourse:(NSString *)strCourseId {

    NSString *username;
    NSString *nologinuser = [WShareUtil getUUID];

    NSDictionary *parametersDict;
    if ([WShareUtil sharedData].dicSession) {
        username = [WShareUtil sharedData].dicSession[@"nsrsbh"];
        if (username == nil) {
            username = @"";
        }
        parametersDict = @{@"content":@{@"apptype":@"ios",@"dto":@{@"from":@"hxjt",@"productId":strCourseId},@"revert":@"remaining",@"username":username},@"mode":@"native",@"service":@"order"};
    }else {
        parametersDict = @{@"content":@{@"apptype":@"ios",@"dto":@{@"from":@"hxjt",@"productId":strCourseId},@"revert":@"remaining",@"nologinuser":nologinuser},@"mode":@"native",@"service":@"order"};
    }

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];

        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];

        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if ([successStr isEqualToString:@"true"]) {

            if (![WShareUtil sharedData].isWDDD) {

                [WShareUtil sharedData].dicBuySymbol = @{@"boughten":@"1",@"chosen":@"0",@"id":strCourseId};
            }
            [WShareUtil showAlert:@"温馨提示" message:@"购买成功"];

            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [WShareUtil showAlert:@"温馨提示" message:returnDic[@"errorInfo"]];
        }

        [WShareUtil sharedData].isWDDD = NO;

        [WShareUtil showWait:NO frame:CGRectZero];

    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}


- (IBAction)btnDeleteClick:(UIButton *)sender {

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"确定删除该订单吗" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alertView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [self reportDeleteMyOrder];
    }
}

- (IBAction)btnPayClick:(UIButton *)sender {
    WLog(@"提交订单");
//    [self reportMyOrderSubmitInvoiceInfo];
    [self createPayView];
}

- (void)loadData {
    IAPProduct *product1 = [IAPProduct new];
    product1.m_buyType = ID_Coin1;

    IAPProduct *product2 = [IAPProduct new];
    product2.m_buyType = ID_Coin2;

    IAPProduct *product3 = [IAPProduct new];
    product3.m_buyType = ID_Coin3;

    IAPProduct *product4 = [IAPProduct new];
    product4.m_buyType = ID_Coin4;

    IAPProduct *product5 = [IAPProduct new];
    product5.m_buyType = ID_Coin5;

    IAPProduct *product6 = [IAPProduct new];
    product6.m_buyType = ID_Coin6;

    IAPProduct *product7 = [IAPProduct new];
    product7.m_buyType = ID_Coin7;

    IAPProduct *product8 = [IAPProduct new];
    product8.m_buyType = ID_Coin8;

    IAPProduct *product9 = [IAPProduct new];
    product9.m_buyType = ID_Coin9;

    IAPProduct *product10 = [IAPProduct new];
    product10.m_buyType = ID_Coin10;

    IAPProduct *product11 = [IAPProduct new];
    product11.m_buyType = ID_Coin11;

    IAPProduct *product12 = [IAPProduct new];
    product12.m_buyType = ID_Coin12;

    IAPProduct *product13 = [IAPProduct new];
    product13.m_buyType = ID_Coin13;

    IAPProduct *product14 = [IAPProduct new];
    product14.m_buyType = ID_Coin14;

    IAPProduct *product15 = [IAPProduct new];
    product15.m_buyType = ID_Coin15;

    IAPProduct *product16 = [IAPProduct new];
    product16.m_buyType = ID_Coin16;

    IAPProduct *product17 = [IAPProduct new];
    product17.m_buyType = ID_Coin17;

    IAPProduct *product18 = [IAPProduct new];
    product18.m_buyType = ID_Coin18;

    IAPProduct *product19 = [IAPProduct new];
    product19.m_buyType = ID_Coin19;

    self.m_productArray = [NSMutableArray arrayWithObjects:product1,product2,product3,product4,product5,product6,product7,product8,product9,product10,product11,product12,product13,product14,product15,product16,product17,product18,product19,nil];
}

// 我的订单中提交订单
- (void)reportMyOrderSubmitInvoiceInfo {
    NSDictionary *dtoDic;
    NSDictionary *parametersDict;
    NSString *username;
    if ([WShareUtil sharedData].dicSession) {
        username = [WShareUtil sharedData].dicSession[@"nsrsbh"];
        if (username == nil) {
            username = @"";
        }

        NSString *strId;
        if (![WShareUtil strNilOrEmpty:self.myOrderModel.ID]){
            strId = self.myOrderModel.ID;
        } else {
            strId = @"";
        }

        NSString *orderNo;
        if (![WShareUtil strNilOrEmpty:self.myOrderModel.ORDERNO]){
            orderNo = self.myOrderModel.ORDERNO;
        } else {
            orderNo = @"";
        }
        [WShareUtil sharedData].orderId = strId;
        dtoDic = @{@"cat":@"0",@"orderId":strId,@"orderNo":orderNo};
        parametersDict = @{@"mode":@"native",@"service":@"order",@"content":@{@"apptype":@"ios",@"revert":@"payorder",@"username":username,@"dto":dtoDic}};
    }

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];

        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
       
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if ([successStr isEqualToString:@"true"]) {
            [WShareUtil sharedData].dicOrder = returnDic;
            [self createPayView];
        } else {
            [WShareUtil showAlert:@"温馨提示" message:returnDic[@"errorInfo"]];
        }
    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}

// 我的订单中删除订单
- (void)reportDeleteMyOrder {

    NSString *username;
    if ([WShareUtil sharedData].dicSession) {
        username = [WShareUtil sharedData].dicSession[@"nsrsbh"];
        if (username == nil) {
            username = @"";
        }
    } else {
        username = @"";
    }

    NSString *strId;
    if (![WShareUtil strNilOrEmpty:self.myOrderModel.ID]){
        strId = self.myOrderModel.ID;
    } else {
        strId = @"";
    }

    NSDictionary *dtoDic = @{@"orderId":strId};

    NSDictionary *parametersDict = @{@"mode":@"native",@"service":@"order",@"apptype":@"ios",@"content":@{@"revert":@"delete",@"username":username,@"dto":dtoDic}};

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];

        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];

        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if ([successStr isEqualToString:@"true"]) {
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [WShareUtil showAlert:@"温馨提示" message:returnDic[@"errorInfo"]];
        }

    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}

- (IBAction)btnJumpVideo:(UIButton *)sender {
    VideoDetailViewController *videoDetailVc = [[VideoDetailViewController alloc]init];
    videoDetailVc.strId = self.myOrderModel.KC_ID;
    [self.navigationController pushViewController:videoDetailVc animated:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self removePayView];
}

@end
